package com.mdp.sms.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.qcloudsms.SmsMultiSenderResult;
import com.mdp.core.utils.DateUtils;
import com.mdp.sms.entity.SmsFlow;
import com.mdp.sms.tencent.client.SendSmsApi;
import com.mdp.sms.tencent.client.SmsSignApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.mdp.core.service.BaseService;
import static com.mdp.core.utils.BaseUtils.*;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;

import com.mdp.sms.entity.SmsSign;
import com.mdp.sms.mapper.SmsSignMapper;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * @author maimeng-mdp code-gen
 * @since 2024-3-6
 */
@Service
public class SmsSignService extends BaseService<SmsSignMapper,SmsSign> {
	static Logger logger =LoggerFactory.getLogger(SmsSignService.class);

	@Autowired
	private SmsSignApi smsSignApi;

	@Autowired
	private SendSmsApi sendSmsApi;

	@Autowired
	private SmsFlowService smsFlowService;

	/**
	 * 添加短信标签
	 * @author lyk
	 * @cdate 2019/9/16 18:35
	 */
	public SmsSign addSmsSign(Map<String,Object> params) {
		SmsSign customerInsertSmsSign=new SmsSign();
		customerInsertSmsSign.setPic((String)params.get("pic"));
		customerInsertSmsSign.setRemark((String)params.get("remark"));
		customerInsertSmsSign.setText((String)params.get("text"));
		customerInsertSmsSign.setInternational((String)params.get("international"));
		customerInsertSmsSign.setCreateDate(DateUtils.getNowDate());
		Map<String,Object> addParams=new HashMap();
		addParams.put("text", (String)params.get("text"));
		addParams.put("international", Integer.valueOf((String)params.get("international")));
		addParams.put("remark", (String)params.get("international"));
		addParams.put("pic", (String)params.get("base64PicURL"));
		Map<String,Object> result=smsSignApi.addSmsSign(addParams);
		if(!ObjectUtils.isEmpty(result.get("result"))&&(Integer)result.get("result")==0) {
			JSONObject j=(JSONObject)result.get("data");
			if(!ObjectUtils.isEmpty(j.get("id"))) {
				customerInsertSmsSign.setId(j.get("id").toString());
			}
			Integer status=(Integer)j.get("status");
			customerInsertSmsSign.setStatus(status.toString());
			this.insert(customerInsertSmsSign);
			return customerInsertSmsSign;
		}
		return null;
	}

	/**
	 * 删除短信标签
	 * @author lyk
	 * @cdate 2019/9/16 18:35
	 */
	public void delSmsSign(SmsSign smsSign) throws Exception{
		Map<String,Object> delParams=new HashMap();
		List<Integer> signIdList=new ArrayList();
		signIdList.add(Integer.valueOf(smsSign.getId()));
		delParams.put("sign_id", signIdList);
		Map<String,Object> result=smsSignApi.delSmsSign(delParams);
		this.deleteByPk(smsSign);
	}

	/**
	 * 编辑短信标签
	 * 待修改的签名对应的签名 ID，待审核或已拒绝状态的签名，才支持修改
	 * https://cloud.tencent.com/document/product/382/8650
	 * @author lyk
	 * @cdate 2019/9/17 11:47
	 */
	public void editSmsSign(Map<String,Object> params) {
		SmsSign customerUpdateSmsSignObject=new SmsSign();
		customerUpdateSmsSignObject.setId((String)params.get("id"));
		customerUpdateSmsSignObject.setInternational((String)params.get("international"));
		customerUpdateSmsSignObject.setRemark((String)params.get("remark"));
		customerUpdateSmsSignObject.setText((String)params.get("text"));
		customerUpdateSmsSignObject.setPic((String)params.get("pic"));
		Map<String,Object> updateParams=new HashMap();
		updateParams.put("remark", customerUpdateSmsSignObject.getRemark());
		updateParams.put("sign_id", Integer.valueOf(customerUpdateSmsSignObject.getId()));
		updateParams.put("text", customerUpdateSmsSignObject.getText());
		updateParams.put("pic", (String)params.get("base64PicURL"));
		Map<String,Object> result=smsSignApi.modifySmsSign(updateParams);
		if(!ObjectUtils.isEmpty(result.get("result"))&&(Integer)result.get("result")==0) {
			JSONObject j=(JSONObject)result.get("data");
			Integer status=(Integer)j.get("status");
			customerUpdateSmsSignObject.setStatus(status.toString());
			this.updateSomeFieldByPk(customerUpdateSmsSignObject);
		}
	}

	/**
	 * 群发短信
	 * @author lyk
	 * @cdate 2019/9/18 10:50
	 * /**
	 * 群发短信
	 * nationCode 国际码"86"表示中国
	 * phoneNumbers 电话号码数组["21212313123", "12345678902", "12345678903"]
	 * templateId 短信模板id
	 * params 短信模板参数
	 * smsSign 短信签名
	 * 最后两个参数
	 */
	public List<SmsFlow> groupSendSms(Map<String, Object> params) {
		String nationCode=(String)params.get("nationCode");
		String mobiles=(String)params.get("mobiles");
		String templateId=(String)params.get("smsTemplateId");
		String smsTtemplateText=(String)params.get("smsTtemplateText");
		String templateParams=(String)params.get("smsTemplateParams");
		String smsSign=(String)params.get("smsSign");
		String branchId=(String)params.get("branchId");
		String shopId=(String)params.get("shopId");
		String locationId=(String)params.get("locationId");
		String userid=(String)params.get("userid");
		String userNeedReplySms=(String)params.get("userNeedReplySms");
		String replyEndDay=(String)params.get("replyEndDay");
		if(!StringUtils.hasText(nationCode)) {
			throw new BizException("请传递国际码nationCode");
		}else if(!StringUtils.hasText(mobiles)) {
			throw new BizException("请传递需要发送的电话号码mobiles");
		}else if(!StringUtils.hasText(templateId)) {
			throw new BizException("请传递需要发送的短信模板Id");
		}else if(!StringUtils.hasText(smsSign)) {
			throw new BizException("请传递需要发送的短信签名smsSign");
		}else if(!StringUtils.hasText(userid)) {
			throw new BizException("请传递需要发送者的用户id");
		}
		String[] mobilesArr=mobiles.split(",");
		String[] paramsArr= {};
		if(StringUtils.hasText(templateParams)) {
			paramsArr=templateParams.split(",");
		}
		//生成拓展好
		String extendNo=SendSmsApi.createExtendNo();
		String regex="\\{\\d+\\}";
		String finallyConverSmsText="";//最终转换的内容
		if(paramsArr.length>0) {
			finallyConverSmsText=SendSmsApi.arrayContentReplaceStringByRegex(smsTtemplateText,regex,paramsArr);
		}
		finallyConverSmsText="【"+smsSign+"】"+finallyConverSmsText;
		SmsMultiSenderResult result=sendSmsApi.groupSendSms(nationCode,mobilesArr, Integer.valueOf(templateId), paramsArr, smsSign,extendNo,"");
		List<SmsMultiSenderResult.Detail> details=result.details;
		List<SmsFlow> smsFlowArray=new ArrayList();
		for(SmsMultiSenderResult.Detail detail:details) {
			SmsFlow smsFlow=new SmsFlow();
			smsFlow=smsFlowService.batchCreateSmsFlow(templateId, finallyConverSmsText, smsSign, templateParams,
					smsTtemplateText, branchId,shopId,locationId,detail.mobile,detail.nationcode,new BigDecimal(detail.fee),
					userid, extendNo, String.valueOf(detail.result),detail.errmsg,userNeedReplySms,replyEndDay);
			smsFlowArray.add(smsFlow);
		}
		smsFlowService.batchInsert(smsFlowArray);
		/*for(SmsFlow s:smsFlowArray) {
			s.setMobile(sendSmsApi.shieldPhone(s.getMobile()));
		}*/
		return smsFlowArray;
	}




	/**
	 * 定时查询腾讯云的短信标签的状态
	 * @throws Exception
	 */
	@Scheduled(cron = "0 0/3 * * * ?")
	public void selectTemplate() throws Exception {
		String strDateFormat = "yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
		SmsSign customerQuerySmsSignObject=new SmsSign();
		customerQuerySmsSignObject.setStatus("1");
		List<SmsSign> smsSignList=this.selectListByWhere(customerQuerySmsSignObject);
		/*customerQuerySmsSignObject.setStatus("2");
		smsSignList.addAll(this.selectListByWhere(customerQuerySmsSignObject));*/
		for(SmsSign s:smsSignList) {
			Map<String,Object> params=new HashMap();
			List<Integer> tplIdList=new ArrayList();
			tplIdList.add(Integer.valueOf(s.getId()));
			params.put("sign_id", tplIdList);
			Map<String,Object> result=smsSignApi.getSmsSign(params);
			if(!ObjectUtils.isEmpty(result.get("result"))&&(Integer)result.get("result")==0) {
				List<JSONObject> dataJSONObjectList=(List<JSONObject>)result.get("data");
				for(JSONObject j:dataJSONObjectList) {
					Integer status=(Integer)j.get("status");
					String reply=(String)j.get("reply");
					String replyTimeStr=(String)j.get("reply_time");
					s.setReply(reply);
					s.setStatus(status.toString());
					s.setReplyDate(sdf.parse(replyTimeStr));
					this.updateSomeFieldByPk(s);
				}
			}
		}
	}

	public static void main(String[] args) {

	}

	public void smsReply(Map<String, Object> params) {
		sendSmsApi.smsReply();
	}

	/**
	 * 自定义查询，支持多表关联
	 * @param page 分页条件
	 * @param ew 一定要，并且必须加@Param("ew")注解
	 * @param ext 如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
	 * @return
	 */
	public List<Map<String,Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String,Object> ext){
		return baseMapper.selectListMapByWhere(page,ew,ext);
	}
}

